<template>
  <div>
    <a-layout-content :style="{ paddingTop: settings.fixedHeader ? '64px' : '0' }">
      <always-multi-tab v-if="$store.getTheme('newTab')=='always'"
                        v-model="pages"
                        ref="multiTab"
                        @tabChange="onTabChange" />
      <default-multi-tab v-if="$store.getTheme('newTab')=='default'"
                         v-model="pages"
                         ref="multiTab"
                         @tabChange="onTabChange" />
    </a-layout-content>

    <!-- RouteView -->
    <a-spin :spinning="$store.state.app.loading">
      <MultiTabRouteView v-if="!reloadRouterView"
                         v-show="!isOpenInIframe"
                         @router-view-title="handleRouterViewTitle"/>
    </a-spin>

    <!-- 内嵌iframe -->
    <template v-for="page in pages">
      <iframe v-if="page.meta.target"
              v-show="page.name==activeTab"
              :key="page.meta.key"
              width="100%"
              height="500px"
              :src="page.path"
              :name="page.name"
              :ref="page.name"
              scrolling="auto"
              :id="page.name"
              @load="onIframeLoad"
              frameborder="0">
      </iframe>
    </template>
  </div>
</template>

<script>
/**
 * 多标签应用布局
 */
import defaultThemes from '../themes/defaults'
import MultiTabRouteView from './MultiTabRouteView.vue'

export default {
  components: { MultiTabRouteView },
  name: 'MultiTabLayout',
  props: {
    reloadRouterView: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      activeTab: '',
      pages: [],
      isOpenInIframe: false,
      settings: {
        fixedHeader: defaultThemes.fixedHeader
      }
    }
  },
  watch: {
    reloadRouterView (n) {
      this.pages.length = 0
    },
    '$route' () {
      this.isOpenInIframe = false
    }
  },
  methods: {
    onIframeLoad (e) {
      // const rect = e.currentTarget.getBoundingClientRect()
      // e.currentTarget.style.position = 'absolute'
      // e.currentTarget.style.top = `${rect.top}px`
      // e.currentTarget.style.bottom = '0px'
      // e.currentTarget.style.left = '0px'
      // e.currentTarget.style.right = '0px'
    },
    handleRouterViewTitle(title, subtitle) {
      this.$refs.multiTab.handleRouterViewTitle(title, subtitle)
    },
    onTabChange (key, page) {
      this.activeTab = key
      this.isOpenInIframe = !!page.target
    },
    openInIframe (page) {
      const current = this.pages.find(p => p.aliveKey == page.aliveKey)
      if (!current) {
        this.pages.push(page)
      }
      this.onTabChange(page.aliveKey, page)
    },
    closeIframe () {
      // this.page = {}
    }
  }
}
</script>

<style lang="less" scoped>
</style>